"""
    Controller for person table. Contains lessons, positions and connected plans tabs.
"""

from turbogears import widgets, expose, redirect, validate, identity
from mnemoply import model
from mnemoply.mass_actions import MassAction
from mnemoply.widgets import DictionaryField
from mnemoply.controllers.lookup import LookupController, TableCol, TableLookupDataSource
from mnemoply.controllers.crud import CRUDController, ItemActionsTab, ItemTab

class MATransformToPartner(MassAction):
    target_class = model.Person
    name = "transform_to_partner"
    title = _("Transform to partner")

    def call(self, objs):
        p_type = model.PartnerType.get(3) #FIXME
        office = identity.current.user.office
        for o in objs:
            model.Partner(
                partnerType=p_type,
                surname=o.surname,
                forename=o.forename,
                patronymic=o.patronymic,
                phone=o.phone,
                email=o.email,
                password=model.Partner.createNewPassword(office),
                office=office
                )

class LessonTab(ItemActionsTab):
    title = _("Lessons")
    name = "lessons_tab"
    ma_class_name = 'SpentLesson'

    def getRecords(self, obj):
        return list(model.SpentLesson.selectBy(teacher=obj))

class PositionsTab(ItemTab):
    title = _("Positions")
    name = "positions_tab"
    template = "../person_position"

    add_form = widgets.TableForm(fields=[
            DictionaryField(
                name="position_id",
                model_object_name='Position',
                not_empty=True,
                label="Position",
            ),
            DictionaryField(
                name="organization_id",
                model_object_name='Organization',
                not_empty=True,
                label=_("Organization"),
            ),
            DictionaryField(
                name="busyness_type_id",
                model_object_name='BusynessType',
                not_empty=True,
                label=_("Busyness type"),
            ),
        ],
        submit_text=_("Add"),
        action='add_position',
    )

    @identity.require(identity.has_any_permission('dba', 'Person/edit'))
    @expose()
    def delete_position(self, obj, position_id):
        model.PersonPosition.get(int(position_id)).destroySelf()
        raise redirect("./")

    @identity.require(identity.has_any_permission('dba', 'Person/edit'))
    @validate(form=add_form)
    @expose()
    def add_position(self, obj, position_id, organization_id, busyness_type_id):
        position = model.Position.get(int(position_id))
        organization = model.Organization.get(int(organization_id))
        busynessType = model.BusynessType.get(int(busyness_type_id))
        model.PersonPosition(person=obj, position=position, organization=organization, busyness=busynessType)

        raise redirect("./")

class PlanTab(ItemTab):
    title = _("Plans")
    name = "plans_tab"
    template = "../person_plan"

    add_form = widgets.TableForm(fields=[
        DictionaryField(
                name="plan_id",
                model_object_name='Plan',
                not_empty=True,
                label="Plan",
            ),
        ],
        submit_text=_("Add"),
        action='add_plan',
    )

    @identity.require(identity.has_any_permission('dba', 'Person/edit'))
    @expose()
    def delete_plan(self, obj, plan_id):
        model.PersonPlan.get(int(plan_id)).destroySelf()
        raise redirect("./")

    @identity.require(identity.has_any_permission('dba', 'Person/edit'))
    @validate(form=add_form)
    @expose()
    def add_plan(self, obj, plan_id):
        model.PersonPlan(person=obj, plan=model.Plan.get(int(plan_id)))
        raise redirect("./")

class PersonController(LookupController, CRUDController):
    model_object = model.Person
    lookup_columns = [
        TableCol(name='surname', caption=_("Surname")),
        TableCol(name='forename', caption=_("Forename")),
        TableCol(name='patronymic', caption=_("Patronymic")),
        TableCol(name='phone', caption=_("Phone"), hidden=True),
        TableCol(name='email', caption="e-mail", hidden=True),
        TableCol(name='comment', caption=_("Comment"), hidden=True),
        TableCol(name='position_str', caption=_("Positions"), hidden=True),
        TableCol(name='office_name', caption=_("Office"), hidden=True),
        TableCol(name='can_teach_str', caption=_("Can teach"), hidden=True),
    ]
    view_fields = [
        'surname', 'forename', 'patronymic',
        'phone', 'email',
        'officeID',
        'comment',
        'canTeach',
    ]

    item_tabs = [PositionsTab(), PlanTab(), LessonTab()]

    def __init__(self):
        LookupController.__init__(self,
            data_source=TableLookupDataSource('person_lookup'),
            columns=self.lookup_columns,
            mass_actions_class=self.model_object,
            title=self.model_object.model_title,
        )
        CRUDController.__init__(self, model_object=self.model_object)

exposed = PersonController()
